<template>
  <header class="header">
    <div class="container">
      <div class="logo-container">
        <router-link to="/" class="logo">
          <img src="../../gallery/xinlogo.png" alt="代码小英雄" class="logo-image">
        </router-link>
      </div>

      <nav class="nav-menu">
        <ul>
          <li v-for="item in navItems" :key="item.id" :class="{ active: isActive(item.route) }">
            <a v-if="item.external" :href="item.route" target="_blank" rel="noopener noreferrer">{{ item.title }}</a>
            <router-link v-else :to="item.route">{{ item.title }}</router-link>
          </li>
        </ul>
      </nav>

      <div class="auth-container">
        <!-- 未登录时显示登录和注册按钮 -->
        <template v-if="!isLoggedIn">
          <router-link to="/login" class="login-btn">
            <i class="icon-user"></i>
            登录
          </router-link>
          <router-link to="/register" class="register-btn">
            <i class="icon-user-plus"></i>
            注册
          </router-link>
        </template>
        
        <!-- 已登录时显示用户下拉菜单 -->
        <UserDropdown 
          v-if="isLoggedIn && userInfo" 
          :user-info="userInfo" 
          @user-logout="handleUserLogout"
        />
      </div>
    </div>
  </header>
</template>

<script>
import UserDropdown from './UserDropdown.vue';
import logger from '../utils/logger.js'

export default {
  name: 'TheHeader',
  components: {
    UserDropdown
  },
  data() {
    return {
      allNavItems: [
        { id: 1, title: '首页', route: '/', roles: [] }, // 所有角色可见
        { id: 2, title: '入门课程', route: 'https://io.codehero.store', external: true, roles: [] }, // 所有角色可见
        { id: 5, title: 'TOC在线编辑器', route: '/goc-editor', roles: [] }, // 所有角色可见
        { id: 6, title: '题目检索', route: '/problems', roles: [1, 2, 5] }, // 仅管理员、教师、家长可见
        { id: 7, title: '比赛', route: '/contests', roles: [] }, // 所有角色可见
        { id: 8, title: '新闻', route: '/news', roles: [1, 2, 5] }, // 仅管理员、教师、家长可见
      ],
      userInfo: null
    };
  },
  computed: {
    // 检查用户是否已登录
    isLoggedIn() {
      try {
        return !!this.userInfo && !!(typeof window !== 'undefined' && window.localStorage && localStorage.getItem('token'));
      } catch (error) {
        logger.warn('⚠️ localStorage访问失败:', error);
        return false;
      }
    },
    
    // 根据用户角色过滤导航项
    navItems() {
      const userRole = this.getUserRole()
      logger.log('🔍 [TheHeader] 当前用户角色:', userRole)
      
      // 如果未登录或角色未知，显示所有导航项
      if (!userRole) {
        return this.allNavItems
      }
      
      // 过滤导航项：如果roles为空数组，表示所有角色可见；否则只显示包含当前角色的项
      const filteredItems = this.allNavItems.filter(item => {
        // roles为空数组表示所有角色可见
        if (item.roles.length === 0) {
          return true
        }
        // 否则检查当前角色是否在允许列表中
        return item.roles.includes(userRole)
      })
      
      logger.log('📋 [TheHeader] 过滤后的导航项数量:', filteredItems.length)
      return filteredItems
    }
  },
  methods: {
    isActive(route) {
      return this.$route && this.$route.path === route;
    },
    
    // 获取当前用户的角色
    getUserRole() {
      try {
        // 首先从JWT令牌中获取role
        const token = localStorage.getItem('token')
        if (token) {
          try {
            const tokenParts = token.split('.')
            if (tokenParts.length === 3) {
              const payloadStr = atob(tokenParts[1])
              
              // 使用正则表达式提取role
              const roleMatch = payloadStr.match(/"role":(\d+)/)
              if (roleMatch && roleMatch[1]) {
                const role = parseInt(roleMatch[1])
                logger.log('👤 [TheHeader] 从JWT令牌获取用户角色:', role)
                return role
              }
              
              // 备用方案：使用JSON.parse
              const payload = JSON.parse(payloadStr)
              const role = payload.claims?.role
              if (role !== undefined) {
                logger.log('👤 [TheHeader] 从JWT claims获取用户角色:', role)
                return parseInt(role)
              }
            }
          } catch (tokenError) {
            logger.warn('⚠️ [TheHeader] JWT令牌解析失败:', tokenError)
          }
        }
        
        // 备选方案：从localStorage获取用户信息
        const userInfoStr = localStorage.getItem('userInfo')
        if (userInfoStr) {
          const userInfo = JSON.parse(userInfoStr)
          const role = userInfo.role
          if (role !== undefined) {
            // role可能是数字或字符串
            const roleNum = typeof role === 'string' ? parseInt(role) : role
            logger.log('👤 [TheHeader] 从localStorage获取用户角色:', roleNum)
            return roleNum
          }
        }
      } catch (error) {
        logger.error('❌ [TheHeader] 获取用户角色失败:', error)
      }
      
      logger.warn('⚠️ [TheHeader] 无法获取用户角色，返回null')
      return null // 返回null表示未知角色
    },
    
    // 检查用户登录状态
    checkUserLoginStatus() {
      let userInfoStr, token;
      
      try {
        if (typeof window !== 'undefined' && window.localStorage) {
          userInfoStr = localStorage.getItem('userInfo');
          token = localStorage.getItem('token');
        } else {
          userInfoStr = null;
          token = null;
        }
      } catch (error) {
        logger.warn('⚠️ localStorage访问失败:', error);
        userInfoStr = null;
        token = null;
      }
      
      logger.log('🔍 [TheHeader] 检查登录状态...');
      logger.log('🔍 [TheHeader] userInfo存在:', userInfoStr ? '是' : '否');
      logger.log('🔍 [TheHeader] token存在:', token ? '是' : '否');
      
      if (userInfoStr) {
        logger.log('🔍 [TheHeader] userInfo内容:', userInfoStr);
      }
      if (token) {
        logger.log('🔍 [TheHeader] token内容:', token);
      }
      
      if (userInfoStr && token) {
        try {
          const parsedUserInfo = JSON.parse(userInfoStr);
          // 确保用户信息完整
          this.userInfo = {
            // 用户名处理：优先使用nickname，备用username，最后用email前缀
            username: parsedUserInfo.nickname || parsedUserInfo.username || parsedUserInfo.email?.split('@')[0] || 'User',
            nickname: parsedUserInfo.nickname || parsedUserInfo.username || 'User',
            email: parsedUserInfo.email || parsedUserInfo.account || '',
            account: parsedUserInfo.account || parsedUserInfo.email || '',
            avatar: parsedUserInfo.avatar || '',
            id: parsedUserInfo.id || null,
            role: parsedUserInfo.role || 'user',
            ...parsedUserInfo
          };
          logger.log('✅ [TheHeader] 用户已登录:', this.userInfo);
          logger.log('✅ [TheHeader] 登录状态检查结果: isLoggedIn =', this.isLoggedIn);
        } catch (error) {
          logger.error('❌ [TheHeader] 解析用户信息失败:', error);
          this.clearUserData();
        }
      } else {
        logger.log('❌ [TheHeader] 用户未登录');
        this.userInfo = null;
      }
      
      logger.log('🎯 [TheHeader] 最终登录状态:', this.isLoggedIn);
      logger.log('🎯 [TheHeader] 最终用户信息:', this.userInfo);
    },
    
    // 清除用户数据
    clearUserData() {
      this.userInfo = null;
      try {
        if (typeof window !== 'undefined' && window.localStorage) {
          localStorage.removeItem('userInfo');
          localStorage.removeItem('token');
          localStorage.removeItem('loginHint'); // 清除登录提示
        }
      } catch (error) {
        logger.warn('⚠️ localStorage清理失败:', error);
      }
      logger.log('用户数据已清除');
    },
    
    // 设置localStorage监听器
    setupStorageListener() {
      // 监听localStorage变化（跨标签页同步）
      this.storageListener = (event) => {
        if (event.key === 'userInfo' || event.key === 'token') {
          logger.log('🔄 [TheHeader] localStorage变化，重新检查用户状态');
          logger.log('🔄 [TheHeader] 变化的key:', event.key);
          logger.log('🔄 [TheHeader] 新值:', event.newValue);
          
          // 延迟检查以确保所有相关的localStorage更新都完成
          setTimeout(() => {
            this.checkUserLoginStatus();
          }, 100);
        }
      };
      
      window.addEventListener('storage', this.storageListener);
      
      // 也监听自定义事件（同标签页内的更新）
      this.userInfoUpdateListener = () => {
        logger.log('🔄 [TheHeader] 用户信息更新事件');
        this.checkUserLoginStatus();
      };
      
      window.addEventListener('userInfoUpdated', this.userInfoUpdateListener);
    },
    
    // 处理用户退出登录
    handleUserLogout() {
      this.userInfo = null;
      logger.log('用户已退出登录');
      
      // 如果当前不在登录页面，刷新页面以更新状态
      if (this.$route.path !== '/login') {
        this.$nextTick(() => {
          window.location.reload();
        });
      }
    }
  },
  
  mounted() {
    logger.log('🚀 TheHeader组件已挂载');
    
    // 组件挂载时检查用户登录状态
    this.checkUserLoginStatus();
    
    // 监听路由变化，检查登录状态
    this.$watch('$route', () => {
      logger.log('🔄 路由变化，重新检查登录状态');
      // 添加延迟以确保localStorage已更新
      this.$nextTick(() => {
        this.checkUserLoginStatus();
      });
    });
    
    // 设置localStorage监听器，实时更新用户状态
    this.setupStorageListener();
  },
  beforeUnmount() {
    logger.log('🧹 [TheHeader] 开始清理事件监听器');
    
    // 清理事件监听器
    if (this.storageListener) {
      window.removeEventListener('storage', this.storageListener);
      this.storageListener = null;
    }
    if (this.userInfoUpdateListener) {
      window.removeEventListener('userInfoUpdated', this.userInfoUpdateListener);
      this.userInfoUpdateListener = null;
    }
    
    logger.log('✅ [TheHeader] 事件监听器已清理');
  }
};
</script>

<style scoped>
.header {
  background-color: #3e8ef7;
  color: white;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.container {
  display: flex;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
  height: 65px; /* 固定高度使布局更稳定 */
}

.logo-container {
  padding: 0;
}

.logo {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: white;
  text-decoration: none;
  display: flex;
  align-items: center;
}

.logo-image {
  height: 40px;
  width: auto;
}

.auth-container {
  padding: 0;
  margin-left: 20px;
}

.login-btn, .register-btn {
  background: none;
  border: 1px solid white;
  color: white;
  padding: 5px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
  text-decoration: none;
  display: inline-block;
  margin-left: 10px;
}

.login-btn:hover, .register-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.nav-menu {
  flex: 1;
  margin: 0 20px;
  display: flex;
  justify-content: center;
}

.nav-menu ul {
  display: flex;
  list-style: none;
  padding: 0;
  margin: 0;
  flex-wrap: nowrap;
}

.nav-menu li {
  padding: 0;
}

.nav-menu a,
.nav-menu a[target="_blank"] {
  color: white;
  text-decoration: none;
  padding: 20px 15px;
  display: block;
  font-size: 15px;
  transition: all 0.2s;
}

.nav-menu li.active a, 
.nav-menu li a:hover,
.nav-menu li a[target="_blank"]:hover {
  background-color: rgba(255, 255, 255, 0.1);
  color: white;
}

.icon-user:before {
  content: "👤";
  margin-right: 4px;
}

.icon-user-plus:before {
  content: "➕";
  margin-right: 4px;
}

@media (max-width: 768px) {
  .container {
    flex-wrap: wrap;
    height: auto;
  }
  
  .logo-container {
    margin-right: auto;
  }

  .nav-menu {
    order: 3;
    width: 100%;
    margin: 0;
    justify-content: flex-start;
    overflow-x: auto;
  }
  
  .nav-menu ul {
    width: max-content;
  }
  
  .nav-menu a,
  .nav-menu a[target="_blank"] {
    padding: 12px 15px;
  }
}
</style> 